/*
 * Copyright (C) 2022 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.arthas.psimobile.fragment.login;


import android.graphics.Color;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;

import com.arthas.psimobile.core.BaseFragment;
import com.arthas.psimobile.utils.UrlAddress;
import com.xuexiang.psimobile.R;
import com.xuexiang.psimobile.databinding.FragmentCertificationBinding;
import com.arthas.psimobile.utils.SettingUtils;
import com.arthas.psimobile.utils.Utils;
import com.arthas.psimobile.utils.XToastUtils;
import com.arthas.psimobile.utils.sdkinit.UMengInit;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.utils.ThemeUtils;
import com.xuexiang.xui.utils.ViewUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

/**
 * 实名认证页面
 *
 * @author Arthas
 * @since 2021-4-1 19:02
 */
@Page(anim = CoreAnim.none)
public class CertificationFragment extends BaseFragment<FragmentCertificationBinding> implements View.OnClickListener {

    public static class RegisterInfo {
        public String phoneNumber;
        public String passwd;
    }

    private View mJumpView;
    private CertificationFragment.RegisterInfo registerInfo;
    private String phoneNumber;
    private String passwd;

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.btn_cert) {
            if (binding.etRealName.validate()) {
                if (binding.etIdCard.validate()) {
                    onCert(binding.etRealName.getEditValue(), binding.etIdCard.getEditValue());
                }
            }
        } else if (id == R.id.tv_privacy_protocol) {
            Utils.gotoProtocol(this, true, true);
        }
    }

    @NonNull
    @Override
    protected FragmentCertificationBinding viewBindingInflate(LayoutInflater inflater, ViewGroup container) {
        return FragmentCertificationBinding.inflate(inflater, container, false);
    }

    @Override
    protected void initViews() {
        registerInfo = deserializeObject((String) this.getArguments().get("registerInfo"), CertificationFragment.RegisterInfo.class);
        phoneNumber = registerInfo.phoneNumber;
        passwd = registerInfo.passwd;
//        if (!SettingUtils.isAgreePrivacy()) {
//            Utils.showPrivacyDialog(getContext(), ((dialog, which) -> {
//                dialog.dismiss();
//                handleSubmitPrivacy();
//            }));
//        }
        boolean isAgreePrivacy = SettingUtils.isAgreePrivacy();
        binding.cbProtocol.setChecked(isAgreePrivacy);
    }

    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle()
                .setImmersive(true);
        titleBar.setBackgroundColor(Color.TRANSPARENT);
        titleBar.setTitle("");
        titleBar.setLeftImageDrawable(ResUtils.getVectorDrawable(getContext(), R.drawable.ic_login_close));
        titleBar.setActionTextColor(ThemeUtils.resolveColor(getContext(), R.attr.colorAccent));

        return titleBar;
    }

    @Override
    protected void initListeners() {
        binding.btnCert.setOnClickListener(this);
//        binding.tvUserProtocol.setOnClickListener(this);
        binding.tvPrivacyProtocol.setOnClickListener(this);
    }

    private void refreshButton(boolean isChecked) {
        ViewUtils.setEnabled(binding.btnCert, isChecked);
        ViewUtils.setEnabled(mJumpView, isChecked);
    }

    private void handleSubmitPrivacy() {
        SettingUtils.setIsAgreePrivacy(true);
        UMengInit.init();
    }

    private void onCert(String realName, String idCard) {

        new Thread() {
            @Override
            public void run() {
                try {
                    Looper.prepare();

                    String requestUrl = UrlAddress.urlAddress + "/account/register";
                    HttpPost request = new HttpPost(requestUrl);

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("phoneNumber", phoneNumber);
                    jsonObject.put("passwd", passwd);
                    jsonObject.put("idCard", idCard);
                    jsonObject.put("name", realName);
                    StringEntity se = new StringEntity(jsonObject.toString(), HTTP.UTF_8);
                    request.setEntity(se);
                    request.addHeader("Content-Type", "application/json");
                    HttpResponse httpResponse = new DefaultHttpClient().execute(request);
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        String retSrc = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
                        JSONObject json = new JSONObject(retSrc);
                        int code = json.getInt("code");
                        if (code == 0) {
                            XToastUtils.success("实名认证成功");
                            openNewPage(LoginFragment.class);
                        } else {
                            XToastUtils.toast(json.getString("msg"));
                        }
                    }
                    Looper.loop();
                } catch (Exception e) {
                    Log.e("Register Eror", e.toString());
                }
            }
        }.start();
    }
}
